#include<bits/stdc++.h>
#define ll long long
#define ull unsigned long long
using namespace std;

const int N = 510, INF = 0x3f3f3f3f;

int n, m;
int a[N][N];
map<int, set<int>> hs;

void solve()
{
    int ans = 0;
    cin >> n >> m;
    for (int i = 1;i <= n;i++)
        for (int j = 1;j <= m;j++) {
            cin >> a[i][j];
            hs[min(i, j)].insert(a[i][j]);
            if (min(i, j) == a[i][j]) ans++;
        }

    for (int i = 1;i <= n;i++)
        for (int j = 1;j <= m;j++) {
            if (a[i][j] == min(i, j)) continue;
            if (hs[a[i][j]].count(min(i, j)) != 0) {
                cout << ans + 2;
                return;
            }
        }

    for (int i = 1;i <= n;i++)
        for (int j = 1;j <= m;j++) {
            if (a[i][j] == min(i, j)) continue;
            if (hs[a[i][j]].size() != hs[a[i][j]].count(a[i][j])) {
                cout << ans + 1;
                return;
            }
        }

    cout << ans;
}

signed main()
{
    //ios::sync_with_stdio(0);
    //cin.tie(0);cout.tie(0);
#define ONLINE_JUDGE
#ifndef ONLINE_JUDGE
    std::istringstream in(R"()");
    std::cin.rdbuf(in.rdbuf());
#endif
    int T = 1;
    //cin>>T;
    for (int i = 1;i <= T;i++) {
        solve();
    }
}